import axios from 'axios'

export const serverHost = import.meta.env.VITE_HOST

axios.defaults.baseURL = serverHost

const http = axios.create()

// 请求拦截
http.interceptors.request.use(
  (config) => {
    config.headers['Content-Type'] = 'application/json'
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截
http.interceptors.response.use(
  (res) => {
    if (res.data.code !== 0 && res.data.code !== 200) {
      return Promise.reject(res.data)
    }
    return res.data
  },
  (error) => {
    return Promise.reject(error)
  }
)

export const request = ({ url, method = 'POST', timeout = 30000, data = {} }) => {
  return new Promise((resolve, reject) => {
    method = method.toLocaleUpperCase()
    http({
      url,
      method,
      timeout,
      params: method !== 'POST' ? data : null,
      data: method === 'POST' ? data : null
    })
      .then(resolve)
      .catch(reject)
  })
}
